package com.github.zhangsken.libcrashreport;

import android.content.Context;
import android.content.Intent;
import android.content.ComponentName;
import android.os.Bundle;

public class CrashHandler implements Thread.UncaughtExceptionHandler {  
    public static final String TAG = CrashHandler.class.getSimpleName();

    private static CrashHandler INSTANCE ;  
    private CRApplication mCRApplication;  

    private CrashHandler() {  

    }  

    public static synchronized CrashHandler getInstance() {  
        if (INSTANCE == null)  
            INSTANCE = new CrashHandler();  
        return INSTANCE;
    }

    public void init(CRApplication cRApplication) {  
        this.mCRApplication = cRApplication;
    }  


    public void uncaughtException(Thread arg0, Throwable arg1) {
        String szMSG = arg1.getClass()
            + "\n\n\n== Exception Message: ==>\n"
            + arg1.getMessage();
        szMSG += "\n\n\n== StackTrace: ==>";
        for (StackTraceElement ste:arg1.getStackTrace()) {
            szMSG += "\n\n>>>FileName: " + ste.getFileName()
                + "\n   ClassName: " + ste.getClassName()
                + "\n   MethodName: " + ste.getMethodName()
                + "\n   LineNumber: " + ste.getLineNumber()
                + "\n   String: " + ste.toString();
        }
        startExceptionViewer(szMSG);

        android.os.Process.killProcess(android.os.Process.myPid());  
    }  

    public void startExceptionViewer(String szMSG) {
        String szCrashApplicationPackageName = mCRApplication.getPackageName();
        Intent intent = new Intent();
        intent.putExtra(CrashViewActivity.EXTRA_MSG, szMSG);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setComponent(new ComponentName(
            szCrashApplicationPackageName, CrashViewActivity.class.getName()));
        mCRApplication.startActivity(intent);
    }
}

